$(function() {
	$('.sale_datetimepicker').datetimepicker({
		format : 'YYYY/MM/DD'
	});

	$("#add_sale_goods").on('click', '.button_delete', function () {
	    $(this).closest('tr').remove();
	});

	$('[name=category]').change(function() {
        var categoryId = $('[name=category] option:selected').val();
        $.ajax({
            url:'sale_get_goods',
            type:'POST',
            data:{
                'categoryId': categoryId
            }
        })
			.done( (data) => {
                console.log(data);
            })
            // Ajaxリクエストが失敗した時発動
            .fail( (data) => {
                console.log(data);
            })
    });
});
function remove(temp){
	$(temp).parent().parent().remove();
}
function cancelSet(){
	window.location.href=('./home');
}
function onSubmitGo(){

	window.history.go(-1);

}
function onSubmit(op,str){

	var start_date = document.getElementById("start_date");
	var end_date = document.getElementById("end_date");
	var goodCodeId = document.getElementById("goodCodeId");

	if(trim(start_date.value)==null || trim(start_date.value)==""){
		alert("開始日を入力してください!");
		start_date.focus();
		return false;
	}
	if(trim(end_date.value)==null || trim(end_date.value)==""){
		alert("終了日を入力してください!");
		end_date.focus();
		return false;
	}
	if(trim(goodCodeId.value)==null || trim(goodCodeId.value)==""){
		alert("商品コードを入力してください!");
		goodCodeId.focus();
		return false;
	}

	if(str == "100"){
		document.getElementById('str').value=str;
	    var form = document.getElementById('setForm');
	    form.action="../set/"+op;
	    form.submit();
	}else{
		var form = document.getElementById('setForm');
		form.action="../set/"+op;
		form.submit();
	}

}
function onSubmitSave(op,str){
	var setNameId = document.getElementById("set_name");
	var start_date = document.getElementById("start_date");
	var end_date = document.getElementById("end_date");

	if(trim(setNameId.value)==null || trim(setNameId.value)==""){
		alert("セット名称を入力してください!");
		setNameId.focus();
		return false;
	}
	if(trim(start_date.value)==null || trim(start_date.value)==""){
		alert("開始日を入力してください!");
		start_date.focus();
		return false;
	}
	if(trim(end_date.value)==null || trim(end_date.value)==""){
		alert("終了日を入力してください!");
		end_date.focus();
		return false;
	}

	var start_date = document.getElementById("start_date");
	var end_date = document.getElementById("end_date");
	var goodCodeId = document.getElementById("goodCodeId");

	var form = document.getElementById('setForm');
	form.action="./set/"+op;
	form.submit();
}
function trim(str){

	   return str.replace(/(^\s*)|(\s*$)/g, "");

 }
function onSubmitDelete(op,goodsID){
	document.getElementById('goods_id').value=goodsID;
	if (false === confirm('削除しますか？') )return;
    var form = document.getElementById('setForm');
    form.action="./set/"+op;
    form.submit();
}
function onSubmitUpdate(op,categoryID,goodsID){
  var oDiv = document.getElementById("divCategory"+goodsID);
  var oDivNm = document.getElementById("divNm"+goodsID);
  var oButton = document.getElementById("btnID"+goodsID);

  if (oDiv.style.display == "none"){
    oDiv.style.display = "block";
    oDivNm.style.display = "none";
    oButton.value = "保存";
   }else {
    oDiv.style.display = "none";
    oDivNm.style.display = "block";
    oButton.value = "修正 ";

    document.getElementById('category_id').value=categoryID;
	document.getElementById('goods_id').value=goodsID;
	var form = document.getElementById('setForm');

	form.action="./set/"+op;
	form.submit();

   }
}
function gotoEdit(set_id){
	var form = document.getElementById('setForm');
	$("#set_id").val(set_id);
	form.method="get";
	form.action="./set_add";
	form.submit();
}
function onSubmitAddSet(){
	window.location.href=('./set_add');
}

(function($){
	$.fn.quickTip = function(url,para,callback){
		var dimension = function(){
			if(!this && !this.offsetLeft){
				return {x:0,y:0};
			}
			var x = this.offsetLeft;
			var y = this.offsetTop;
			var p = this.parentElement;
			while(p){
				x = x + p.offsetLeft;
				y = y + p.offsetTop;
				p = p.offsetParent;
			}
			return {x:x,y:y};
		}

		$(".suggestion").each(function(){
			var $sp = $("");
			var dim = dimension.call(this);
			var w = $(this).width();
			$(this).css({padding:'0px 0px 0px 0px'});
			$(this).parent().append($sp);
			var lh = $(this).height()+"px";
			var dim = dimension.call(this);
			$sp.css({'line-height':lh,top:dim.y+1,left:dim.x,'z-index':$(this).css('z-index')+1});
			//$(this).after($sp);
			var obj = this;
			$sp.click(function(){wim.apply(obj);stopBubble();});
			$(this).keyup(keyTip);
		});
		function keyTip(ev){
			if(!ev.ctrlKey && !ev.altKey && !ev.shiftKey){
				if(ev.which >= 96 || ev.which <= 111 || ev.which == 8 || ev.which >= 48 && ev.which <= 57 || ev.which >=65 && ev.which <= 90){
					wim.apply(this,[$(this).val()]);
				}
			}

		}

		var wim = function (key){
			if(!key){
				key = "";
			}
			var $this = $(this);
			$("#tip_div").hide();
			var tableStyle = "font-size:14px;width:100%";
			var reStr = "<font style='color:red;font-weight:bold'>"+key+"</font>";
			var reg = eval("/"+key+"/g");
			if(para){
				para['searchKey'] = key;
			}
			var data = para ? para : {key:key};
			$.ajax({url:url,data:data,dataType:'json',type:'post',success:function(d,st,res){
				var str = "<table style='"+tableStyle+"' id='contentList' >";
				var ht = 0
				$(d).each(function(){
					if(true){
						ht = ht + 28;
						var v = key == "" ? this.name : this.name.replace(reg,reStr);
						v = this.id + "(" + v + ")";
						str += "<tr><td nowrap objectid='"+$this.attr("id")+"' id='"+this.id+"' style='height:30px;cursor:pointer;border-bottom:1px solid #FFB6C1' title='"+this.name+"'  goodsid='"+this.goodsid+"'>"+v+"</td></tr>";
					}

				});

				str += "</table>";
				var dim = dimension.call($this.get(0));
				dim.y = dim.y + $this.height()+6;
				$("#tip_div").html(str).css({top:dim.y,left:dim.x,'min-width':$this.width(),width:$this.width()+25}).show();

				injectVal.call($("#contentList"));
			},complete:function(d,st,xhr){
				//alert(st)
			}});
		}

		var injectVal = function(){
			this.find("td").click(function(){
				setValue(this);
			});
		}

		$(document).bind('click',function(){
			$("#tip_div").hide();
		});

		$(document).bind('keydown',function(ev){
			if(ev.which == 38 ){//up
				var curr = getCurrentTr();
				var nt;
				if(curr != null){
					$(curr).removeClass("c");
					$(curr).css("background","#efefef");
					nt = $(curr).prev();
				}

				if(!nt){
					nt = $("#contentList").find("tr:last");
				}
				if(nt && nt.length > 0){
					nt.addClass("c");
					nt.css("background","#afafaf");
					var pos = nt.get(0).offsetTop;
					setScrollTop(pos);
				}

			}else if(ev.which == 40){//down
				var curr = getCurrentTr();
				var nt;
				if(curr != null){
					$(curr).removeClass("c");
					$(curr).css("background","#efefef");
					nt = $(curr).next();
				}
				if(!nt){
					nt = $("#contentList").find("tr:first");
				}
				if(nt && nt.length > 0){
					nt.addClass("c");
					nt.css("background","#afafaf");
					var pos = nt.get(0).offsetTop;
					setScrollTop(pos);
				}

			}else if(ev.which == 13){
				var c = $("#contentList").find(".c").find("td");
				if(c.length > 0){
					setValue(c);
					stopBubble();
				}
			}
		})

		function getCurrentTr(){
			var c = null;
			$("#contentList").find("tr").each(function(){
				var clz = $(this).attr("class");
				if(clz == 'c'){
					c = this;
					return false;
				}
			});
			return c;
		}

		createDiv();
		function createDiv(){
			var div = $("<div id='tip_div'> </div>");
			div.css({background:'#FFFFFF',position:'absolute',display:'none',height:'190px',overflow:'auto',border:'1px solid #1E90FF','z-index':9999});
			$(document.body).append(div);
		}
		function setScrollTop(pos){
			pos = pos - 10 > 0 ? pos - 10 : 0;
			$("#tip_div").animate({scrollTop:pos},100);
		}
		function stopBubble(){
			window.event.returnValue = false;
			window.event.cancelBubble = true;
		}
		function setValue(o){
			   var objectid = $(o).attr("objectid");
			   var val = $(o).attr("title");
			   var id  = $(o).attr("id");
			   var goodsid = $(o).attr("goodsid");
			   var index = objectid.split("_")[1];

			   $("#"+objectid).val(id);
			   $("#tip_div").hide();
			   if(callback){
			    var o = new Object();
			    o.id = id;
			    o.name = val;
			    callback(o);
			    $("#goodsId_"+index).val(goodsid);
			    $("#goodsCode_"+index).val(id);
			    $("#goodsName_"+index).val(val);
			   }
	    }
	}
	})(jQuery);
